mui.init({
	//	preloadPages:[{
	//		id:'invest_record_page',
	//		url:'../invest_record/invest_record.html'
	//	}]
});
var old_back = mui.back;
mui.back = function() {
	// var btn = ["确定","取消"];
	//mui.confirm('确认关闭当前窗口？','提示',btn,function(e){
	//  if(e.index==0){
	plus.webview.getLaunchWebview().show();
	plus.webview.currentWebview().close();
	//  }
	// });
}
mui.plusReady(function() {
	var self = plus.webview.currentWebview();
	var formId = self.formId;
	var sessionId = plus.storage.getItem(KeyCfg.JSESSIONID);

	(function() {
		var targetPageId = plus.webview.currentWebview().id;
		plus.storage.setItem(KeyCfg.targetPageId, targetPageId);
		var buy_base_record = CmwMcore.$("buy_base_record");
		MeventMgr.onTouchstart(buy_base_record, function(event, self) {
			var cfg = {
				pars: {
					formId: formId
				}
			};
			MuiEventMgr.open('../buybase/buybase.html', cfg);
		});

		var buy_list_record = CmwMcore.$("buy_list_record");
		MeventMgr.onTouchstart(buy_list_record, function(event, self) {
			var cfd = {
				pars: {
					formId: formId
				}
			};
			MuiEventMgr.open('../buyrecord/buyrecord.html', cfd);
		});

	})();

	/*---- 初始化数据 ---*/
	(function initData() {
		var url = UrlConfig.minvest_trans_detail;
		var formDatas = {
			transferLoanId: formId,
			sessionId: sessionId
		};
		$.ajax(url, {
			data: formDatas,
			dataType: 'jsonp',
			crossDomain: true,
			success: function(data) {
				data = JSON.parse(data);
				renderData(data);
			}
		});
	})();

	function darkbackground() {
		var d = $(".darkbackground");
		d.css("background-color", "#000");
	}


	/**
	 * 将数据渲染到页面
	 * @param {Object} data
	 */
	function renderData(data) {
		var success = data.success;
		if (!success) return;
		var id = data.id;
		var loanRecordId = data.loanRecordId;
		var discountRate = data.discountRate;
		var loanTitle = data.loanTitle;
		var tenderMoney = data.tenderMoney;
		var rateYear = data.rateYear;
		var refundDeadline = data.refundDeadline;
		var period = data.period;
		var sellMoney = data.sellMoney;
		var effectiveYield = data.effectiveYield;
		var status = data.status;
		var cashBalance = data.cashBalance;
		var hongbao = data.hongbao;
		var fromUserId = data.fromUserId;
		var paymentDate = data.paymentDate;
		var repayrate = data.repayrate;
		var fee = data.fee;
		var thisMonthInterest = data.thisMonthInterest;
		var discountMoney = data.discountMoney;
		$("#transferloanId").val(id);
		$("#cashBalance").val(cashBalance);
		$("#loan_hongbao").val(hongbao);
		$("#sellMoney").val(sellMoney);
		$("#fromUserId").val(fromUserId);
		if (sellMoney && parseFloat(sellMoney) > 0) sellMoney = CmwMcore.getThousandths(sellMoney);
		if (tenderMoney && parseFloat(tenderMoney) > 0) tenderMoney = CmwMcore.getThousandths(tenderMoney);
		if (cashBalance && parseFloat(cashBalance) > 0) cashBalance = CmwMcore.getThousandths(cashBalance);

		$("#label_loanTitle").text(loanTitle);
		$("#loan_sellMoney").text(sellMoney);
		$("#label_tenderMoney").text(tenderMoney);
		$("#label_rateYear").text(rateYear);
		$("#label_refundDeadline").text(refundDeadline);
		$("#label_period").text(period);
		$("#label_effectiveYield").text(effectiveYield);
		$("#loanRecordId").text(loanRecordId);
		$("#discountRate").text(discountRate);
		$("#label_sellMoney").text(sellMoney);
		$("#loan_cashBalance").text(cashBalance);
		$("#sp_hongbao").text(hongbao);
		$("#loan_paymentDate").text("每月" + paymentDate + "日");
		$("#loan_status").text(status);
		$("#loan_repayrate").text(repayrate);
		$("#loan_fee").text(fee);
		$("#loan_thisMonthInterest").text(thisMonthInterest);
		$("#loan_discountMoney").text(discountMoney);
		controlRight(status, hongbao);
	}

	/**
	 * 权限控制
	 * @param {Object} status
	 */
	function controlRight(status, hongbao) {
		var btn_buy = $("#btn_buy");
		if ("购买" == status) {
			btn_buy.text("投标");
			btn_buy.removeAttr('disabled');
			$("#tr_argee").show();
		} else {
			btn_buy.text(status);
			btn_buy.attr("disabled", "disabled");
			var a = $(".app_buy_inf");
			a.css("margin-top", "150px");
			var b = $(".mui-orange");
			b.css("color", "#606060");
			$("#tr_argee").hide();
			$("#app_buy_panel").hide();
		}
		if (!hongbao || parseFloat(hongbao) <= 0) {
			$("#tr_hongbao").hide();
		} else {
			$("#tr_hongbao").show();
		}
	}

	/**
	 * 我要投标
	 */
	$("#btn_buy").click(function() {
		MuiEventMgr.checkSessionByRemote(function(){
			var dis=$("#btn_buy").attr("disabled")//判断是否有这属性
			if(dis)return; 
			var flag = validForm();
			if (!flag) return false;
			submitForm();
		},function(){
			var win = plus.webview.getWebviewById(appid);
			win.evalJS("activeTabItemPage('userAccount');");
			window.setTimeout(function(){win.show();},1000);
		});
		return false;
	});

	/**
	 * 验证表单
	 */
	function validForm() {
		var flag = true;
		//amount,argee,hongbao
		//minBuyMoney,cashBalance,loan_hongbao
		var minBuyMoney = $("#minBuyMoney").val();
		var amount = $("#sellMoney").val();
		var cashBalance = $("#cashBalance").val();
		var loan_hongbao = $("#loan_hongbao").val();

		amount = parseFloat(amount);
		if (!cashBalance || parseFloat(cashBalance) < 0) {
			mui.alert("您的可用余额为0,请先充值后再购买!");
			return false;
		}


		if (amount > parseFloat(cashBalance)) {
			mui.alert("您的可用余额低于购买金额,请先充值后再购买!!");
			return false;
		}

		if ($("input[name='hongbao']").is(":checked")) {
			var buyAmount = amount + parseFloat(loan_hongbao);
			if (buyAmount > cashBalance) {
				mui.alert("可用余额不足，请先充值后再购买!");
				return false;
			}
		}

		if (!$("input[name='agree']").is(":checked")) {
			mui.alert("您还没有同意《来理财债权转让协议》!");
			return false;
		}
		return flag;
	}

	/**
	 * 提交表单（买标）
	 */
	function submitForm() {
		CmwMcore.disabled('btn_buy');
		var url = UrlConfig.minvest_payAmountDetail;
		var amount = $("#sellMoney").val();
		if ($("input[name='hongbao']").is(":checked")) {
			var formDatas = {
				count: amount,
				hongbaos: "1"
			};
			$.ajax(url, {
				data: formDatas,
				dataType: 'jsonp',
				crossDomain: true,
				success: function(data) {
					data = JSON.parse(data);
					var msg = data.content;
					msg = msg.replace("<br/>", "\n");
					saveDatas(msg, amount);
				}
			});
		} else {
			var msg = "当前标购买价格：" + amount + "元,确认购买吗?";
			saveDatas(msg, amount);
		}
	}

	function saveDatas(msg, amount) {
		mui.confirm(msg, '来理财', {
			'确定': 'ok',
			'取消': 'no'
		}, function(e) {
			if (e.index == 0) {
				var hongbaos = '';
				if ($("input[name='hongbao']").is(":checked")) {
					hongbaos = '1';
				}
				var sessionId = plus.storage.getItem(KeyCfg.JSESSIONID);
				var userId = plus.storage.getItem(KeyCfg.userId);

				var url = UrlConfig.minvest_trans_save;
				var transferloanId = $("#transferloanId").val();
				var formDatas = {
					transferloanId: transferloanId,
					hongbaos: hongbaos,
					sessionId: sessionId,
					userId: userId
				};
				$.ajax(url, {
					data: formDatas,
					dataType: 'jsonp',
					crossDomain: true,
					success: function(data) {
						CmwMcore.enabled('btn_buy');
						data = JSON.parse(data);
						var msg = data.msg;
						var success = data.success;
						if (!success) {
							if (!msg) msg = "购买失败!";
							mui.alert(msg);
						} else {
							msg = "购买成功!";
							mui.alert(msg);
							var indexPage = plus.webview.getLaunchWebview();
							plus.storage.setItem(KeyCfg.currClickTabId, "invest");  
							/*此处使用的HTML 原生 localStorage ，是因为在 invest.js 激活选项卡时是在 mui.init 初始化之前，故不能用 plus.storage*/
							localStorage.setItem(KeyCfg.invest_activeTabItem, "transfer");
							indexPage.show();
							mui.fire(indexPage, 'refresh', {});
							var win = plus.webview.getWebviewById(appid);
		        			win.show();
		        			win.evalJS("activeTabItemPage('invest','1');");    

							/*tabHeader2:是投资记录页面的 回款的投资选项卡*/
							//	        			var cfg = {pars : {activeTabItemId:'tabHeader2'}};
							////					var cfg = {pars : {}};
							//					MuiEventMgr.openBySafe('../invest_record/invest_record.html',cfg);
						}
					}
				});
			} else {
				CmwMcore.enabled('btn_buy');
				return;
			}
		});
	}

	var a_agree = CmwMcore.$("a_agree");
	MeventMgr.onTouchstart(a_agree, function(event, self) {
		var loanRecordId = $("#loanRecordId").text();
		var discountRate = $("#discountRate").text();
		var fromUserId = $("#fromUserId").val();
		console.log("fromUserId=" + fromUserId);
		//		plus.storage.setItem(KeyCfg.tran_loanRecordId,loanRecordId);
		//		plus.storage.setItem(KeyCfg.tran_discountRate,discountRate);
		var cfg = {
			pars: {
				loanRecordId: loanRecordId,
				discountRate: discountRate,
				fromUserId: fromUserId
			}
		};
		MuiEventMgr.openBySafe('../protocol/tranProtocol.html', cfg);
		return false;
	});

});